<template>
  <div class="borrow-manage">
    <div class="page-header">
      <h1>借阅管理</h1>
      <p>管理系统中的所有借阅记录</p>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <div class="search-form">
        <el-form :model="searchForm" inline>
          <el-form-item label="用户ID">
            <el-input 
              v-model="searchForm.userId" 
              placeholder="请输入用户ID"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="图书ID">
            <el-input 
              v-model="searchForm.bookId" 
              placeholder="请输入图书ID"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select 
              v-model="searchForm.status" 
              placeholder="请选择状态"
              clearable
              style="width: 150px"
            >
              <el-option label="借阅中" value="BORROWED" />
              <el-option label="已归还" value="RETURNED" />
              <el-option label="已逾期" value="OVERDUE" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchRecords" :icon="Search">搜索</el-button>
            <el-button @click="resetSearch" :icon="Refresh">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <div class="table-header">
        <h3>借阅记录 ({{ pagination.total }}条记录)</h3>
        <div class="header-actions">
          <el-button @click="exportRecords" :icon="Download">导出</el-button>
        </div>
      </div>
      
      <el-table :data="borrowRecords" v-loading="loading" stripe>
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column label="借阅ID" prop="id" width="80" />
        <el-table-column label="用户ID" prop="userId" width="80" />
        <el-table-column label="用户姓名" prop="userName" width="120" />
        <el-table-column label="图书ID" prop="bookId" width="80" />
        <el-table-column label="图书名称" prop="bookName" min-width="200" show-overflow-tooltip />
        <el-table-column label="借阅日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.borrowDate) }}
          </template>
        </el-table-column>
        <el-table-column label="应还日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.returnDate) }}
          </template>
        </el-table-column>
        <el-table-column label="实际归还日期" width="130">
          <template #default="{ row }">
            {{ row.actualReturnDate ? formatDate(row.actualReturnDate) : '未归还' }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewDetail(row)" :icon="View">详情</el-button>
            <el-button 
              v-if="row.status === 'BORROWED'"
              size="small" 
              type="success"
              @click="forceReturn(row)"
              :icon="Check"
            >
              强制归还
            </el-button>
            <el-button 
              v-if="row.status === 'BORROWED'"
              size="small" 
              type="warning"
              @click="renewBook(row)"
              :icon="Refresh"
            >
              续借
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailVisible" title="借阅详情" width="600px">
      <div v-if="currentRecord" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="借阅ID">{{ currentRecord.id }}</el-descriptions-item>
          <el-descriptions-item label="用户ID">{{ currentRecord.userId }}</el-descriptions-item>
          <el-descriptions-item label="用户姓名">{{ currentRecord.userName }}</el-descriptions-item>
          <el-descriptions-item label="图书ID">{{ currentRecord.bookId }}</el-descriptions-item>
          <el-descriptions-item label="图书名称" :span="2">{{ currentRecord.bookName }}</el-descriptions-item>
          <el-descriptions-item label="借阅日期">{{ currentRecord.borrowDate }}</el-descriptions-item>
          <el-descriptions-item label="应还日期">{{ currentRecord.returnDate }}</el-descriptions-item>
          <el-descriptions-item label="实际归还日期">
            {{ currentRecord.actualReturnDate || '未归还' }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentRecord.status)">
              {{ getStatusText(currentRecord.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ currentRecord.remark || '无' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 续借对话框 -->
    <el-dialog v-model="renewVisible" title="续借图书" width="400px">
      <el-form :model="renewForm" label-width="80px">
        <el-form-item label="续借天数">
          <el-input-number 
            v-model="renewForm.days" 
            :min="1" 
            :max="30"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="renewVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRenew" :loading="renewLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Download, View, Check } from '@element-plus/icons-vue'
import request from '@/utils/request'

const loading = ref(false)
const borrowRecords = ref([])
const detailVisible = ref(false)
const renewVisible = ref(false)
const renewLoading = ref(false)
const currentRecord = ref(null)

const searchForm = ref({
  userId: '',
  bookId: '',
  status: ''
})

const pagination = ref({
  current: 1,
  size: 10,
  total: 0
})

const renewForm = ref({
  id: null,
  days: 7
})

// 获取借阅记录列表
const fetchBorrowRecords = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.value.current,
      size: pagination.value.size,
      ...searchForm.value
    }

    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await request.get('/borrows/page', { params })
    if (response.code === 200) {
      const data = response.data
      borrowRecords.value = data.records || []
      pagination.value.total = data.total || 0
    }
  } catch (error) {
    console.error('获取借阅记录失败:', error)
    ElMessage.error('获取借阅记录失败')
  } finally {
    loading.value = false
  }
}

// 状态处理函数
const getStatusType = (status) => {
  const statusMap = {
    'BORROWED': 'warning',
    'RETURNED': 'success', 
    'OVERDUE': 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    'BORROWED': '借阅中',
    'RETURNED': '已归还',
    'OVERDUE': '已逾期'
  }
  return statusMap[status] || '未知'
}

// 日期格式化函数
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 搜索相关方法
const searchRecords = () => {
  pagination.value.current = 1
  fetchBorrowRecords()
}

const resetSearch = () => {
  searchForm.value = {
    userId: '',
    bookId: '',
    status: ''
  }
  pagination.value.current = 1
  fetchBorrowRecords()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.value.size = size
  pagination.value.current = 1
  fetchBorrowRecords()
}

const handleCurrentChange = (current) => {
  pagination.value.current = current
  fetchBorrowRecords()
}

// 查看详情
const viewDetail = async (record) => {
  try {
    const response = await request.get(`/borrows/${record.id}`)
    if (response.code === 200) {
      currentRecord.value = response.data
      detailVisible.value = true
    }
  } catch (error) {
    console.error('获取借阅详情失败:', error)
    ElMessage.error('获取借阅详情失败')
  }
}

// 强制归还
const forceReturn = (record) => {
  ElMessageBox.confirm(
    `确定要强制归还《${record.bookName}》吗？`,
    '强制归还确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const response = await request.post(`/borrows/return/${record.id}`)
      if (response.code === 200) {
        ElMessage.success('强制归还成功')
        fetchBorrowRecords()
      } else {
        ElMessage.error(response.message || '强制归还失败')
      }
    } catch (error) {
      console.error('强制归还失败:', error)
      ElMessage.error('强制归还失败，请重试')
    }
  }).catch(() => {
    // 用户取消
  })
}

// 续借
const renewBook = (record) => {
  renewForm.value.id = record.id
  renewForm.value.days = 7
  renewVisible.value = true
}

const confirmRenew = async () => {
  renewLoading.value = true
  try {
    const response = await request.post(`/borrows/renew/${renewForm.value.id}`, null, {
      params: { days: renewForm.value.days }
    })
    if (response.code === 200) {
      ElMessage.success('续借成功')
      renewVisible.value = false
      fetchBorrowRecords()
    } else {
      ElMessage.error(response.message || '续借失败')
    }
  } catch (error) {
    console.error('续借失败:', error)
    ElMessage.error('续借失败，请重试')
  } finally {
    renewLoading.value = false
  }
}

// 导出记录
const exportRecords = () => {
  ElMessage.info('导出功能开发中...')
}

onMounted(() => {
  fetchBorrowRecords()
})
</script>

<style scoped>
.borrow-manage {
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  font-size: 24px;
  color: #333;
  margin: 0 0 8px 0;
}

.page-header p {
  color: #666;
  margin: 0;
}

.search-card {
  margin-bottom: 16px;
}

.table-card {
  margin-bottom: 24px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.table-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding: 20px 0;
}

.detail-content {
  padding: 16px 0;
}

:deep(.el-table th) {
  background-color: #fafafa !important;
}

:deep(.el-card__header) {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-card__body) {
  padding: 20px;
}
</style> 